package com.farmer.h5.webview;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.view.View;
import android.webkit.GeolocationPermissions;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.widget.ProgressBar;

public class FWebChromeClient extends WebChromeClient
{
    private FWebSettings fwebSettings;
    
    private ProgressBar progressbar;
    
    public static final int FILECHOOSER_RESULTCODE = 5173;
    
    private ValueCallback<Uri> mUploadMessage;
    
    private Context context;
    
    public void setProperty(FWebSettings fwebSettings, Context context)
    {
        this.fwebSettings = fwebSettings;
        this.context = context;
    }
    
    public void setProgressbar(ProgressBar progressbar)
    {
        this.progressbar = progressbar;
    }
    
    @Override
    public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions.Callback callback)
    {
        if (fwebSettings.isUseGps)
        {
            callback.invoke(origin, true, false);
        }
        super.onGeolocationPermissionsShowPrompt(origin, callback);
    }
    
    @Override
    public void onProgressChanged(WebView view, int newProgress)
    {
        if (null != progressbar)
        {
            if (newProgress == 100)
            {
                progressbar.setProgress(95);
                progressbar.setProgress(98);
                progressbar.setProgress(100);
                progressbar.setVisibility(View.GONE);
            }
            else
            {
                if (progressbar.getVisibility() == View.GONE)
                {
                    progressbar.setVisibility(View.VISIBLE);
                }
                progressbar.setProgress(newProgress);
            }
        }
        super.onProgressChanged(view, newProgress);
    }
    
    /**
     * 为了兼容文件上传 3.0-  /  3.0  /  4.1+
     */
    public void openFileChooser(ValueCallback<Uri> uploadMsg)
    {
        this.openFileChooser(uploadMsg, "*/*");
    }
    
    public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType)
    {
        this.openFileChooser(uploadMsg, acceptType, null);
    }
    
    public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture)
    {
        mUploadMessage = uploadMsg;
        Intent i = new Intent(Intent.ACTION_GET_CONTENT);
        i.addCategory(Intent.CATEGORY_OPENABLE);
        i.setType("image/*");
        ((Activity)context).startActivityForResult(Intent.createChooser(i, "File Browser"), FILECHOOSER_RESULTCODE);
    }
    
    public ValueCallback<Uri> getValueCallback()
    {
        return this.mUploadMessage;
    }
    
}